<template>
	<view class="container"
		style="color:white;height: 100%;width: 100%;display: flex;flex-direction: column;background-image: linear-gradient(to bottom, #092E72 0%, #070F24 100%);">
		<view class="box" style="display: flex;justify-content: space-between;margin:0rpx 15rpx">
			<view class="box" style="font-size: 60rpx;display: flex;justify-content: center;align-items: center;">
				<image style="height: 60rpx;width: 60rpx;" src="/static/svg/home-wifi-fill.svg"></image>
				家庭环境监测
			</view>
			<view class="box" style="display: flex;align-items: center;">
				<view>设备在线</view>
				<view>✅</view>
			</view>
		</view>
		<view class="box" style="flex:1; display: flex;padding:10px 30rpx;">
			<image style="width: 100%; height: 100%; background-color: #000000;border-radius: 30rpx;" mode="aspectFit"
				:src="base64_img"></image>
				<text style="font-size: 20rpx;position: absolute;top: calc(50% - 130rpx);right:40rpx;color: white;">每5秒获取一次图像</text>
		</view>
		<view class="box" style="flex:1; display: flex;padding:10px 30rpx;flex-direction: column;gap: 30rpx;">
			<view class="box" style="flex:1; display: flex;gap: 30rpx;">
				<view class="box data_box"	style="background-image: linear-gradient(to top, #F54E48 0%, #FDAE69 100%);">
					<view style="height: 30rpx;padding: 8rpx;">室内温度</view>
					<view class="tem_hum_num" style="">
						{{temper}}℃
					</view>
				</view>
				<view class="box data_box"	style="background-image: linear-gradient(to top, #316FF1 0%, #30D4F3 100%);">
					<view style="height: 30rpx;padding: 8rpx;">室内湿度</view>
					<view class="tem_hum_num" >
						{{humidity}}%
					</view>
				</view>
			</view>
			<view class="box" style="flex:1; display: flex;gap: 30rpx;">
				<view class="box"
					style="flex:1;display: flex;flex-direction: column;background-color: #747A85;border-radius: 30rpx;">
					<view style="padding: 8rpx;">烟雾状态</view>
					<view style="display: flex;flex-direction: column;align-items: center;font-size: 70rpx;flex:1">
						<image :src="isAlarming?'/static/svg/alarming.svg':'/static/svg/ok.svg'" mode="" style="height:100rpx;width: 100rpx;"></image>
						<view style="font-size: 30rpx;">
							{{isAlarming?"报警":"正常"}}
						</view>
					</view>
				</view>
				<view class="box"
					style="flex:1;display: flex;flex-direction: column;background-color: #747A85;border-radius: 30rpx;">
					<view style="padding: 8rpx;">风机状态</view>
					<view style="display: flex;flex-direction: column;align-items: center;font-size: 70rpx;flex:1">
						<image :class="(isFanNormallyOpen || isAlarming)? 'spin_element' :''" src="/static/svg/fan.svg" mode="" style="height:100rpx;width: 100rpx;"></image>
						<view style="font-size: 30rpx;">
							{{(isFanNormallyOpen || isAlarming)? "开启" :"关闭"}}
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="box"
			style="display: flex;height: 200rpx;background-color: #1E2738;border-radius: 80rpx 80rpx 0rpx 0rpx;align-items: center;">
			<view class="divider"></view>
			<view class="box" style="flex:1;display: flex;align-items: center;justify-content: center;">
				<button type="primary"
					style="width:80%;height: 100rpx;border-radius: 50rpx;background-color: #F75E3D;display: flex;align-items: center;justify-content: center;"
					@click="controlFan"
				>
					{{isFanNormallyOpen || isAlarming? "关闭风机" :"开启风机"}}
					</button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		onMounted,
		ref,
	} from "vue"
	import mqtt from "mqtt"
	const temper = ref(26.4)
	const humidity = ref(40.1)
	const isAlarming = ref(false)
	const isFanNormallyOpen = ref(false)
	const isSystemOnline = ref(false)
	const base64_img = ref();
	const options = {
		keepalive: 1000,
		// Clean session
		protocolVersion: 4,
		clean: false,
		connectTimeout: 40000,
		// 认证信息
		clientId: '68733f9032771f177b4b99f9_monitor1_0_0_2025072815',
		username: '68733f9032771f177b4b99f9_monitor1',
		password: 'abf592e2d5cfdab1c7fbe5c1f3bfd264c7628ef08e46803089f520cdbf558959',
	}
	const shadowTimer = null
	const client = mqtt.connect('wss://99dc6497df.st1.iotda-device.cn-north-4.myhuaweicloud.com:443/mqtt', options)
	client.on('connect', function() {
		console.log('Connected')
		requestDeviceShadow();
		setInterval(()=>requestDeviceShadow(),5000);
	})

	client.on('error', function(error) {
		console.log(error)
	})

	// 重连回调
	client.on('reconnect', function() {
		console.log('正在重连...')
	})

	// 断开连接回调
	client.on('close', function() {
		console.log('连接已断开')
	})

	// 请求设备影子的方法
	function requestDeviceShadow() {
		const requestId = Date.now().toString() // 生成唯一requestId
		const shadowTopic = `$oc/devices/68733f9032771f177b4b99f9_monitor1/sys/shadow/get/request_id=${requestId}`
		// 发送请求（空 payload 即可）
		client.publish(shadowTopic, JSON.stringify({
			id: requestId
		}), (err) => {
			if (err) {
				console.log(`请求影子失败: ${err.message}`)
			} else {
				console.log(`已发送影子请求，requestId: ${requestId}`)
			}
		})
	}

	// 监听信息
	client.on('message', (topic, message) => {
		console.log('收到消息 - 主题:', topic);
		//console.log('收到消息 - 内容:', message.toString()); // 关键：打印二进制消息转为字符串
		if(message.length > 200){
			base64_img.value = `data:image/jpeg;base64,${message}`
		}
		if (topic.startsWith(`property_update_topic`) && message.indexOf('temper')>-1) {
			try {
				const messageStr = typeof message === 'string' ? message : String.fromCharCode.apply(null,
				message);
				//console.log('messageStr', messageStr)
				const messageObj = JSON.parse(messageStr)
				temper.value = messageObj.temper
				humidity.value = messageObj.humidity
				isAlarming.value = messageObj.isAlarming
				isFanNormallyOpen.value = messageObj.isFanNormallyOpen
			} catch (e) {}
		}
		// 匹配影子响应的Topic
		if (topic.startsWith(
			`$oc/devices/68733f9032771f177b4b99f9_monitor1/sys/shadow/get/response/request_id=`)) {
			try {
				const messageStr = typeof message === 'string' ? message : String.fromCharCode.apply(null,
				message);
				//console.log('messageStr', messageStr)
				const messageObj = JSON.parse(messageStr)
				if (messageObj) {
					base64_img.value = `data:image/jpeg;base64,${messageObj.shadow[0].reported.properties.img}`
				}
			} catch (e) {
				// this.log(`解析影子响应失败: ${e.message}`)
			}
		}
	})

	client.subscribe('property_update_topic', {}, function(error, granted) {
		if (error) {
			console.log(error)
		} else {
			console.log(`${granted[0].topic} was subscribed`)
		}
	})
	client.subscribe('$oc/devices/68733f9032771f177b4b99f9_monitor1/sys/shadow/get/response/#', {}, function(error,
		granted) {
		if (error) {
			console.log(error)
		} else {
			console.log(`${granted[0].topic} was subscribed`)
		}
	})
	
	const controlFan = ()=>{
		if(isFanNormallyOpen.value || isAlarming.value){
			// 说明风机开着，那就发送关闭
			client.publish("$oc/devices/68733f9032771f177b4b99f9_monitor1/sys/messages/up",JSON.stringify({
				command:0
			}))
		} 
		else
		{
			client.publish("$oc/devices/68733f9032771f177b4b99f9_monitor1/sys/messages/up",JSON.stringify({
				command:1
			}))
		}
	}
</script>

<style>
	.tem_hum_num {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		font-size: 70rpx;
	}
	.data_box{
		flex:1;display: flex;flex-direction: column;
		border-radius: 30rpx;
	}
	
	/* 定义关键帧动画 */
	@keyframes spin {
	from {
	transform: rotate(0deg);
	}
	to {
	transform: rotate(360deg);
	}
	}
	.spin_element{
		animation: spin 2s linear infinite; 
	}
</style>